import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class CustomsDeclarationPage extends StatefulWidget {
  const CustomsDeclarationPage({Key? key});

  @override
  _CustomsDeclarationPageState createState() => _CustomsDeclarationPageState();
}

class _CustomsDeclarationPageState extends State<CustomsDeclarationPage> {
  Map<String, dynamic>? _responseData;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("海关申报"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: _submitCustomsDeclaration,
              child: const Text("提交海关申报"),
            ),
            const SizedBox(height: 20),
            if (_responseData != null) _buildResponseCard(_responseData!),
          ],
        ),
      ),
    );
  }

  Widget _buildResponseCard(Map<String, dynamic> data) {
    return Card(
      elevation: 4.0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.0),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (!data["status"]) ...[
              _buildResponseRow("状态", data["status"] ? "成功" : "失败"),
              _buildResponseRow("消息", data["message"]),
            ] else ...[
              _buildResponseRow("状态", data["status"] ? "成功" : "失败"),
              _buildResponseRow("消息", data["message"]),
              _buildResponseRow("代码", data["code"].toString()),
              _buildResponseRow("消息", data["message"]),
              _buildResponseRow("App Key", data["app_key"]),
              _buildResponseRow("签名", data["sign"]),
              _buildResponseRow("签名方法", data["sign_method"]),
              _buildResponseRow("时间", data["time"]),
              if (data.containsKey("data") && data["data"] is Map) ...[
                const SizedBox(height: 10),
                const Text(
                  "业务信息",
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                _buildResponseRow("业务编号", data["data"]["business_no"]),
              ]
            ]
          ],
        ),
      ),
    );
  }

  Widget _buildResponseRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        children: [
          Text(
            "$label: ",
            style: const TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
          Expanded(
            child: Text(
              value,
              overflow: TextOverflow.ellipsis,
              maxLines: 10,
            ),
          ),
        ],
      ),
    );
  }

  // 提交海关申报
  void _submitCustomsDeclaration() async {
    String timestamp = DateTime.now().millisecondsSinceEpoch.toString();

    var data = {
      "app_key": "mh_8d0296880ef09834",
      "timestamp": timestamp,
      "v": 1.0,
      "sign_method": "MD5",
      "sign": "123456",
      "data": {
        "service_info": {
          "o_business_no": "",
          "type": 1,
          "o_business_type": "9610",
          "o_business_name": "2024052802批次零售出口",
          "o_ebc_name": "广州伟星电子商务有限公司",
          "o_trading_mall_link": "https://cbec-mall.gzport.net/",
          "o_ebp_name": "CHEEHON CO.,LTD",
          "o_platform_buyer": "CHEEHON CO.,LTD",
          "o_supply_name": "东莞伟星服装厂",
          "o_declare_name": "广州伟星电子商务有限公司",
          "o_logistics_name": "广州伟星运输有限公司",
          "o_transport_name": "深圳市货拉拉运输有限公司",
          "o_transport_abroad_name": "深伟星国际货运代理有限公司",
          "o_pay_name": "招商银行股份有限公司"
        },
        "service_base_info": {
          "o_export_contract": "ECK202405280002",
          "o_deal_curr": "美元",
          "o_price_term": "FOB",
          "o_freight_fee": "0",
          "o_insurance_fee": "0",
          "o_settle_date": "2024-05-31",
          "o_ebc_name": "广州伟星电子商务有限公司",
          "o_ebc_ename": "WEIXIN",
          "o_ebc_contact": "Weixing Zhang",
          "o_ebc_contact_tell": "+86-18620202525",
          "o_ebc_address": "广州市海珠区仑头路21号",
          "o_ebc_eaddress": "21 Luntou Road, Haizhu District, Guangzhou City",
          "o_plat_name": "CHEEHON CO.,LTD",
          "o_plat_ename": "CHEEHON CO.,LTD",
          "o_plat_contact": "SUSAN",
          "o_plat_contact_tell": "001-202-495-2266",
          "o_plat_address": "",
          "o_plat_eaddress":
              "3505 International Place,N.W. Washington,D.C.20008 U.S.A.",
          "o_special": "0",
          "o_ship_date": "2024-05-27",
          "o_pack_way": "4",
          "o_ship_way": "4",
          "o_ship_port": "广州",
          "o_country": "美国",
          "o_country_port": "华盛顿",
          "o_export_note": ""
        },
        "order_info": [
          {
            "o_order_no": "20240528000002",
            "o_pay_no": "P20240528000002",
            "o_waybill_no": "SF20240528000002",
            "o_charge": "100",
            "o_goods_value": "100",
            "o_currency": "502",
            "o_accounting_date": "20240528121312",
            "o_traf_mode": 5,
            "o_country": "502",
            "o_order_note": "",
            "order_goods_info": [
              {
                "o_classification": "衣服",
                "o_goods_ename": "dress",
                "o_goods_cname": "连衣裙",
                "o_goods_sku": "SP00001",
                "o_goods_num": "1",
                "o_goods_price": "100",
                "o_goods_total": 100,
                "o_goods_link": "http:// xxxx.com/....",
                "o_goods_enterprice": "广州市XXX服装有限公司",
                "o_goods_ingrediant": "棉100%",
                "o_goods_note": ""
              }
            ]
          }
        ]
      }
    };

    try {
      var response = await Dio().post(
        'https://cbec-studapi.gzport.net/api/access_service/apply_service',
        data: data,
      );

      setState(() {
        if (response.statusCode == 200) {
          _responseData = response.data;
        } else {
          _responseData = {
            "status": false,
            "message": "请求失败，状态码：${response.statusCode}"
          };
        }
      });
    } catch (e) {
      setState(() {
        _responseData = {"status": false, "message": "请求出错：$e"};
      });
    }
  }
}
